﻿using Microsoft.EntityFrameworkCore;
using System;
using Volo.Abp.EntityFrameworkCore.Modeling;

namespace Volo.Abp.LanguageManagement.EntityFrameworkCore
{
    public static class LanguageManagementDbContextModelCreatingExtensions
	{
		public static void ConfigureLanguageManagement(this ModelBuilder builder, Action<LanguageManagementModelBuilderConfigurationOptions> optionsAction = null)
		{
			Check.NotNull<ModelBuilder>(builder, nameof(builder));
			var options = new LanguageManagementModelBuilderConfigurationOptions(
				LanguageManagementDbProperties.DbTablePrefix,
				LanguageManagementDbProperties.DbSchema
			);
			optionsAction?.Invoke(options);

			builder.Entity<Language>(b =>
			{
				b.ToTable<Language>(options.TablePrefix + "Languages", options.Schema);
				b.ConfigureByConvention();
				b.Property<string>(x => x.CultureName).IsRequired().HasMaxLength(LanguageConsts.MaxCultureNameLength);
				b.Property<string>(x => x.UiCultureName).IsRequired().HasMaxLength(LanguageConsts.MaxUiCultureNameLength);
				b.Property<string>(x => x.DisplayName).IsRequired().HasMaxLength(LanguageConsts.MaxDisplayNameLength);
				b.Property<string>(x => x.FlagIcon).IsRequired().HasMaxLength(LanguageConsts.MaxFlagIconLength);
				b.Property<bool>(x => x.IsEnabled).IsRequired();
			});

			builder.Entity<LanguageText>(b =>
			{
				b.ToTable<LanguageText>(options.TablePrefix + "LanguageTexts", options.Schema);
				b.ConfigureByConvention();
				b.Property<string>(x => x.ResourceName).IsRequired().HasMaxLength(LanguageTextConsts.MaxResourceNameLength);
				b.Property<string>(x => x.Name).IsRequired().HasMaxLength(LanguageTextConsts.MaxKeyNameLength);
				b.Property<string>(x => x.Value).IsRequired().HasMaxLength(LanguageTextConsts.MaxValueLength);
				b.Property<string>(x => x.CultureName).IsRequired().HasMaxLength(LanguageTextConsts.MaxCultureNameLength);
				b.HasIndex(x => new { x.TenantId, x.ResourceName, x.CultureName });
			});
		}
	}
}
